<?php

namespace app\admin\controller;

use think\Db;
use think\facade\Env;
use think\facade\Request;
use think\facade\View;

class Database
{
    protected $db_back;
    use \traits\controller\Jump;
    public function __construct()
    {
        $config=[
            'path'=>str_replace('\\','/',Env::get('root_path')).'Data/',
            'part'=>20971520,
            'compress'=>1,
            'level'=>9
        ];
        //这里的参数可传可不传
        $this->db_back=new \tp5er\Backup($config);
    }

    /**
     * 数据库列表页
     * @return \think\response\View
     */
    public function index()
    {
        //分配列表页面
        $data = Db::query('SHOW TABLE STATUS');
        View::share(['title' => '数据库备份', 'data' => $data]);
        return view();
    }

    /**
     * 表格优化
     */
    public function optimize()
    {
        $select = Request::param('ids');
        if (!$select) $this->error('请选择优化的表');
        $list = Db::query("OPTIMIZE TABLE {$select}");
        if ($list) {
            return json(['code' => 1, 'msg' => '数据表' . $select . '优化完成']);
        } else {
            return json(['code' => 0, 'msg' => '数据表' . $select . '优化失败']);
        }
    }

    /**
     * 数据库表修复
     */
    public function repaire()
    {
        $select = Request::param('ids');
        if (!$select) $this->error('请选择要修复的表');
        $list = Db::query("REPAIR TABLE {$select}");
        if ($list) {
            return json(['code' => 1, 'msg' => '数据表' . $select . '修复完成']);
        } else {
            return json(['code' => 0, 'msg' => '数据表' . $select . '修复失败']);
        }
    }

    /**
     * 数据库备份
     */
    public function backup()
    {
        //1.检测备份目录是否存在,不存则创建
        //2.检测是否有正在执行的任务,通过lock文件.有则error提示,没有创建lock文件
        //3.检测目录是否可写
        $file = ['name' => date('Ymd-His'), 'part' => 1];
        $tables = Request::param('ids');
        $arr = explode(',', $tables);
        foreach ($arr as $v) {
            $back = $this->db_back->setFile($file)->backup($v, 0);
        }
        // $tables="数据库表1";
        return ($back === 0) ? ['code' => 1, 'msg' => '备份成功'] : ['code' => 0, 'msg' => '备份失败'];
    }

    /**
     * 获取数据库备份列表
     * @return mixed
     */
    public function back_list()
    {
        $list = $this->db_back->fileList();
        View::share(['dblist' => $list, 'title' => '数据还原']);
        return view();
    }
     /**
     * 数据库恢复
     */
    public function restore()
    {
        $file=['name'=>date('Ymd-His','1523100045'),'part'=>1];
        $start=0;
        $f= $this->db_back->setFile($file)->import($start);
        dump($f);
    }
    /*
     * 数据库备份删除
     */
    public function back_del()
    {
        $t = Request::param('time');
        $name=date('Ymd-His',$t).'-*.sql*';
        //路径+文件名
        $res = $this->db_back->delFile($t);
        $jarr = ($res) ? ['code' => 1, 'msg' => '删除成功'] : ['code' => 0, 'msg' => '删除失败'];
        return json($jarr);
    }

}
